package com.markhsiu.minimq.remote.transport.talentaio;

import java.io.IOException;

import com.markhsiu.minimq.channel.ChannelProcessor;
import com.markhsiu.minimq.message.Message;
import com.markhsiu.minimq.serialize.SerializeCodec;
import com.talent.aio.common.Aio;
import com.talent.aio.common.ChannelContext;

public class TalenAioChannelAdapterProcessor implements ChannelProcessor<Message>{

	private ChannelContext<Object, MessagePacket, Object> channel;
	private SerializeCodec<Message> codec; 
	
	@SuppressWarnings("unused")
	private  TalenAioChannelAdapterProcessor() {}
	
	public TalenAioChannelAdapterProcessor(ChannelContext<Object, MessagePacket, Object> channel,  SerializeCodec<Message> codec){
		this.channel = channel;
		this.codec = codec;
	}
	
	@Override
	public void write(Message message) {
		writeAndFlush(message);
	}

	@Override
	public void flush() {}

	@Override
	public void writeAndFlush(Message message) {
		try {
			byte[] data = codec.serialize(message);
			MessagePacket resppacket = new MessagePacket();
			resppacket.setBody(data);
			
			Aio.send(channel, resppacket);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
